/**
 * @(#) HealthchkreqMediator.as
 *
 * @date		2009. 05. 07.
 * @version		1.0
 * @author		Shin, Yunwoo
 * @description	건강검진 신청 - Mediator
 * 				건강검진을 조회하고 신청하는 Presentation Logic을 관리 
 */
package com.skt.common_hr.healthcheckup.view
{
	import com.skt.common_hr.common.Variables;
	import com.skt.common_hr.common.components.CommonAlert;
	import com.skt.common_hr.common.puremvc.OverViewMediator;
	import com.skt.common_hr.healthcheckup.HealthCheckUpFacade;
	import com.skt.common_hr.healthcheckup.events.HealthchkreqEvent;
	import com.skt.common_hr.healthcheckup.events.HealthchkreqWriteEvent;
	import com.skt.common_hr.healthcheckup.events.HospitalEvent;
	import com.skt.common_hr.healthcheckup.model.ClosingDayProxy;
	import com.skt.common_hr.healthcheckup.model.HealthCheckUpProxy;
	import com.skt.common_hr.healthcheckup.model.HospitalProxy;
	import com.skt.common_hr.healthcheckup.model.vo.HospitalDefaultVO;
	import com.skt.common_hr.healthcheckup.view.components.HealthCheckUpOverView;
	import com.skt.common_hr.healthcheckup.view.components.HealthchkreqWriteView;
	import com.skt.common_hr.healthcheckup.view.components.OpinionView;
	import com.wcl.utils.DateUtil;
	
	import flash.events.Event;
	
	import mx.collections.ArrayCollection;
	import mx.managers.PopUpManager;
	
	import org.puremvc.as3.multicore.interfaces.INotification;

	public class HealthCheckUpMediator extends OverViewMediator
	{
		public static const NAME:String = "HealthchkreqMediator"; 
		
		private var STCD2:String;

		/**
		* 생성자
		* 
		* @param
		* @return void
		*/
        public function HealthCheckUpMediator( viewComponent:Object )
        {
            super( NAME, viewComponent );
        }
 		
		/**
		* View를 초기화 한다.
		*	- View에 기본사항을 출력하고 data를 load
		* @param
		* @return void
		*/
		override protected function activatedView():void
		{
			setEventListeners();
			loadData();
 			view.vsCompensation.selectedIndex = 0;
		}
		
		override protected function closedView():void
		{
			removeEventListeners();
		}
 		private function setEventListeners():void
 		{
			view.addEventListener(HealthchkreqEvent.SELECTED_ITEM, onSelectedItem);
			view.addEventListener(HealthchkreqWriteView.AGO_OPEN, onAgoOpen);
			view.addEventListener(HealthCheckUpOverView.EVENT_VIEW_OPINION, onViewOpinion);
			view.HealthchkreqWriteView.addEventListener(HealthchkreqWriteEvent.SAVE, onHealthchkreqSave);
			view.HealthchkreqWriteView.addEventListener(HospitalEvent.SELECTED_HOSPITAL, onSelectedHospital);
			view.HealthchkreqWriteView.addEventListener(HealthchkreqWriteView.CHOICE_MONEY_CHECK, onCHoiceMoneyChecK);
 		}
 		
 		private function removeEventListeners():void
 		{
			view.removeEventListener(HealthchkreqEvent.SELECTED_ITEM, onSelectedItem);
			view.removeEventListener(HealthchkreqWriteView.AGO_OPEN, onAgoOpen);
			view.HealthchkreqWriteView.removeEventListener(HealthchkreqWriteEvent.SAVE, onHealthchkreqSave);
			view.HealthchkreqWriteView.removeEventListener(HealthchkreqWriteView.CHOICE_MONEY_CHECK, onCHoiceMoneyChecK);
			view.HealthchkreqWriteView.removeEventListener(HospitalEvent.SELECTED_HOSPITAL, onSelectedHospital);
 		}
 		
 		private function loadData():void
 		{
 			var proxy:HealthCheckUpProxy = facade.retrieveProxy(HealthCheckUpProxy.NAME) as HealthCheckUpProxy;
			proxy.load(Variables.myPernr);
			
			//신청마감일체크
			var closingProxy:ClosingDayProxy = facade.retrieveProxy(ClosingDayProxy.NAME) as ClosingDayProxy;
			closingProxy.loadClosingDay();

 			var hospitalProxy:HospitalProxy = facade.retrieveProxy(HospitalProxy.NAME) as HospitalProxy;
 			hospitalProxy.loadList();
 		}
 		
 		//신청버튼
 		private function onSelectedItem(event:HealthchkreqEvent):void
 		{
 			commonFacade.setStatusMessage("");
 			view.vsCompensation.selectedIndex = 1;
 			view.HealthchkreqWriteView.STCD2  = event.selectedItemVo.STCD2;
 			view.HealthchkreqWriteView.MEDCK  = event.selectedItemVo.MEDCK;
 			view.HealthchkreqWriteView.MEDCKT = event.selectedItemVo.MEDCKT;
 			
 			//창훈 수정  ( null체크 )
 			if(event.selectedItemVo.MREDAT != null){
	 			view.HealthchkreqWriteView.MREDATDAY = String(event.selectedItemVo.MREDAT.month += 1);
	 			
	 			var day:Date = event.selectedItemVo.MREDAT;
	 			day.month += -1;
 			}
 			
 			view.HealthchkreqWriteView.MREDAT = DateUtil.toDefaultString(day);
 			view.HealthchkreqWriteView.MEDCD  = event.selectedItemVo.MEDCD;
 			
 			//신청버튼 
 			if(ClosingDayProxy(facade.retrieveProxy(ClosingDayProxy.NAME)).outOfDate) {
				view.HealthchkreqWriteView.writeBtn.visible = false;
			} else {
				view.HealthchkreqWriteView.writeBtn.visible = true;
			}
			
			view.HealthchkreqWriteView.dgHospital.selectedIndex 
					= findCodeIndexHospital(view.HealthchkreqWriteView.STCD2, view.HealthchkreqWriteView.hospitalList);
			view.HealthchkreqWriteView.onClickDgHospital();
 		}
 		
 		//이전버튼
 		private function onAgoOpen(event:Event):void
 		{
 			view.vsCompensation.selectedIndex = 0;
 			loadData();
 		}
 		
 		//저장
 		private function onHealthchkreqSave(evnet:HealthchkreqWriteEvent):void
 		{
 			var proxy:HealthCheckUpProxy = facade.retrieveProxy(HealthCheckUpProxy.NAME) as HealthCheckUpProxy;
 			proxy.save(Variables.myPernr, evnet._year, evnet.writeSaveVo);
 		}
 		
 		private function onCHoiceMoneyChecK(event:Event):void
 		{
 			if(view.HealthchkreqWriteView.choice != null && view.HealthchkreqWriteView.choice != null && view.HealthchkreqWriteView.proposalsData != null) {
 				if(this.STCD2 == view.HealthchkreqWriteView.STCD2) {
 					var monthIdx:String = String(view.HealthchkreqWriteView.MREDATDAY);
	 				
	 				if(monthIdx.length < 2) {
	 					monthIdx = "0"+String(view.HealthchkreqWriteView.MREDATDAY);
	 				}
	 				
	 				if(monthIdx == view.HealthchkreqWriteView.proposalsDay.selectedItem.data) {
			 			changeIndex();
		 			}
 				}
 			}
 			
 		}
 		
 		//병원목록클릭
 		private function onSelectedHospital(event:HospitalEvent):void
 		{
 			//창훈 수정 (null 체크)
 			if(event.hospitalVo != null){
	 			//var proxy:HealthCheckUpProxy = facade.retrieveProxy(HealthCheckUpProxy.NAME) as HealthCheckUpProxy;
	 			var proxy:HospitalProxy = facade.retrieveProxy(HospitalProxy.NAME) as HospitalProxy;
	 			this.STCD2 = event.hospitalVo.STCD2;
	 			view.HealthchkreqWriteView.hospitalCode = event.hospitalVo.STCD2;	//병원코드
	 			proxy.loadDetail(event.hospitalVo.STCD2);							//병원상세정보
	 			proxy.loadSelectableItems(event.hospitalVo.STCD2);					//선택진료항목
 			}
 		}
 		
 		private function onLoadClosingDay(proxy:ClosingDayProxy):void
 		{
 			if(proxy.outOfDate) {
				view.btnRequest.visible = false;
			} else {
				view.btnRequest.visible = true;
			}
 		}
 		
 		private var opinionView:OpinionView = null;
 		private function onViewOpinion(e:Event):void
 		{
 			//trace(view.dg1.selectedIndex);
 			if(opinionView == null) {
 				opinionView = PopUpManager.createPopUp(view.root, OpinionView, true) as OpinionView;
 				PopUpManager.centerPopUp(opinionView);
 			}
 			else {
 				PopUpManager.addPopUp(opinionView, view.root, true);
 			}
 			opinionView.setFocus();
 			opinionView.opinion = view.examinDataProvider.getItemAt(view.dg1.selectedIndex).OPINION;
 		}
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Process MVC Messages
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
		/**
		* 본 Class에서 처리해야할 Noti들을 등록한다.
		* 
		* @param
		* @return void
		*/
		override public function listNotificationInterests():Array 
		{
			return basicInterestMessages.concat( [
					HealthCheckUpFacade.LOAD_Healthchkreq_LIST_COMPLETE,
					HealthCheckUpFacade.LOAD_Healthchkreq_LIST_FAILED,
					HealthCheckUpFacade.LOAD_END_DAY_COMPLETE,
					HealthCheckUpFacade.LOAD_END_DAY_FAILED,
					HealthCheckUpFacade.LOAD_HOSPITAL_LIST_COMPLETE,
					HealthCheckUpFacade.LOAD_HOSPITAL_LIST_FAILED,
					HealthCheckUpFacade.LOAD_CHOICE_COMBO_LIST_COMPLETE,
					HealthCheckUpFacade.LOAD_CHOICE_COMBO_LIST_FAILED,
					HealthCheckUpFacade.LOAD_HOSPITAL_DEFAULT_COMPLETE,
					HealthCheckUpFacade.LOAD_HOSPITAL_DEFAULT_FAILED,
					HealthCheckUpFacade.LOAD_SAVE_COMPLETE,
					HealthCheckUpFacade.LOAD_SAVE_FAILED
					]);
		}
		

		/**
		* Noti별로 처리한다.
		* 
		* @param
		* @return void
		*/
		override public function handleNotification(note:INotification):void
		{
			super.handleNotification(note);
			switch(note.getName()) 
			{
				case HealthCheckUpFacade.LOAD_Healthchkreq_LIST_COMPLETE:
					onSuccessDataLoad(note.getBody() as HealthCheckUpProxy);
					break;
				case HealthCheckUpFacade.LOAD_Healthchkreq_LIST_FAILED:
					trace("LoadHealthchkreqListFailed");
					break;
				case HealthCheckUpFacade.LOAD_END_DAY_COMPLETE:
				case HealthCheckUpFacade.LOAD_END_DAY_FAILED:
					onLoadClosingDay(note.getBody() as ClosingDayProxy);
					break;
				case HealthCheckUpFacade.LOAD_HOSPITAL_LIST_COMPLETE:
					onHospitalLoad(note.getBody() as HospitalProxy);
					break;
				case HealthCheckUpFacade.LOAD_HOSPITAL_LIST_FAILED:
					trace("LoadHospitalListFailed");
					break;
				case HealthCheckUpFacade.LOAD_CHOICE_COMBO_LIST_COMPLETE:
					onChoiceDataLoad(note.getBody() as HospitalProxy);
					break;
				case HealthCheckUpFacade.LOAD_CHOICE_COMBO_LIST_FAILED:
					trace("LoadChoiceComboListFailed");
					break;
				case HealthCheckUpFacade.LOAD_HOSPITAL_DEFAULT_COMPLETE:
					onDefaultDataLoad(note.getBody() as HospitalProxy);
					break;
				case HealthCheckUpFacade.LOAD_HOSPITAL_DEFAULT_FAILED:
					trace("LoadHospitalDefaultFailed");
					break;
				case HealthCheckUpFacade.LOAD_SAVE_COMPLETE:
					view.vsCompensation.selectedIndex = 0;
					loadData();
					break;
				case HealthCheckUpFacade.LOAD_SAVE_FAILED:
					CommonAlert.showMessage(commonFacade.bundle, (note.getBody() as HealthCheckUpProxy).message);
					break;
				default:
					//trace(this.instanceID+"에서 처리 안된 Noti가 검출됨 : " + note.getBody());
					break;
			}
		}
		
		
		
		/**
		 * Proxy에서 DataLoad를 완료한 후 호출됨
		 *     - load된 데이터를 화면에 출력
		 * @param
		 * @return void
		 */
 		private function onSuccessDataLoad(proxy:HealthCheckUpProxy):void
 		{
 			view.examinDataProvider = proxy.dataList;
 			commonFacade.setStatusMessage("STATUS_LOADED_LIST", [view.examinDataProvider.length]);
 		}
 		
 		private function onHospitalLoad(proxy:HospitalProxy):void
 		{
 			view.HealthchkreqWriteView.hospitalList = proxy.hospitalList;
 			//view.HealthchkreqWriteView.HealthchkreqHospital.hospitalData = proxy.hospitalList;
 			//if(view.HealthchkreqWriteView.STCD2 != null && proxy.hospitalList != null) {
	 		//	view.HealthchkreqWriteView.HealthchkreqHospital.hospitalList.selectedIndex = findCodeIndexHospital(view.HealthchkreqWriteView.STCD2, proxy.hospitalList);
	 		//	view.HealthchkreqWriteView.HealthchkreqHospital.hospitalIdx();
 			//}
 		}
 		
 		private function onChoiceDataLoad(proxy:HospitalProxy):void
 		{
 			view.HealthchkreqWriteView.choice = proxy.selectableItems;
 			changeIndex();
 		}
 		
 		private function onDefaultDataLoad(proxy:HospitalProxy):void
 		{
 			if(proxy.hospitalDetail.length != 0) {
	 			view.HealthchkreqWriteView.vo = proxy.hospitalDetail[0] as HospitalDefaultVO;
 			}
 			view.HealthchkreqWriteView.attached_url = proxy.attached_url;
 			view.HealthchkreqWriteView.dataList = proxy.reservableDate;
 			view.HealthchkreqWriteView.month = proxy.reservableMonthList;
 			changeIndex();
 		}
 		
 		private function changeIndex():void
 		{
 			//선택항목
 			if(view.HealthchkreqWriteView.MEDCK != null) {
 				if(this.STCD2 == view.HealthchkreqWriteView.STCD2) {
	 				if(findCodeIndex(view.HealthchkreqWriteView.MEDCD, view.HealthchkreqWriteView.choice) != -1) {
		 				view.HealthchkreqWriteView.HealthchkreqChoice.selectedIndex = findCodeIndex(view.HealthchkreqWriteView.MEDCD, view.HealthchkreqWriteView.choice);
	 				} else {
	 					view.HealthchkreqWriteView.HealthchkreqChoice.selectedIndex = 0;
	 				}
	 			} else {
	 				view.HealthchkreqWriteView.HealthchkreqChoice.selectedIndex = 0;
	 			}
 			}
 			
 			//월
 			if(view.HealthchkreqWriteView.MREDATDAY != null) {
 				if(this.STCD2 == view.HealthchkreqWriteView.STCD2) {
 					var monthIdx:String = String(view.HealthchkreqWriteView.MREDATDAY);
	 				
	 				if(monthIdx.length < 2) {
	 					monthIdx = "0"+String(view.HealthchkreqWriteView.MREDATDAY);
	 				}
	 				
	 				if(findCodeIndex(monthIdx, view.HealthchkreqWriteView.month) != -1) {
		 				view.HealthchkreqWriteView.proposalsDay.selectedIndex = findCodeIndex(monthIdx, view.HealthchkreqWriteView.month);
		 				view.HealthchkreqWriteView.changeMoneyCheck();
	 				} else {
	 					view.HealthchkreqWriteView.proposalsDay.selectedIndex = 0;
	 				}
 				} else {
 					view.HealthchkreqWriteView.proposalsDay.selectedIndex = 0;
 				}
 			}
 			view.HealthchkreqWriteView.changeMoneyCheck();
 			
 			//예약가능일
 			if(view.HealthchkreqWriteView.proposalsData != null) {
	 			view.HealthchkreqWriteView.proposals.selectedIndex = findCodeIndexGrid(view.HealthchkreqWriteView.MREDAT, view.HealthchkreqWriteView.proposalsData);
 			}
 		}
 		
 		private function findCodeIndex(key:String, srcArr:ArrayCollection):int 
		{
			for(var i:int=0; i<srcArr.length; i++) {
				if(srcArr[i].data == key) {
					return i;
				}
			}
			return -1;
		}
		
		private function findCodeIndexGrid(key:String, srcArr:ArrayCollection):int 
		{
			for(var i:int=0; i<srcArr.length; i++) {
				if(srcArr[i].REDAT_F == key) {
					return i;
				}
			}
			return -1;
		}
		
		private function findCodeIndexHospital(key:String, srcArr:ArrayCollection):int 
		{
			for(var i:int=0; i<srcArr.length; i++) {
				if(srcArr[i].STCD2 == key) {
					return i;
				}
			}
			return -1;
		}
 
 	
 
 
 
 
 
 
 
 		
		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Event handler (from View, Internal or....)
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
 		
 		
 		




		///////////////////////////////////////////////////////////////////////////////////////////////////
		//
		//	Utility Functions
		//
		///////////////////////////////////////////////////////////////////////////////////////////////////
        private function get view():HealthCheckUpOverView
        {
            return viewComponent as HealthCheckUpOverView;
        }
		
		
	}
}